package com.example.eccdemo;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.util.Set;

/**
 * @author golangdorid@gmail.com
 * @date 3/15/21 9:43 PM.
 * @
 */
class KeyUtil {
	public static KeyPair createKeyPairGenerator() {
		KeyPair keyPair;
		try {

		/*	java.security.Provider[] providers = java.security.Security
				.getProviders();

			for (java.security.Provider p : providers) {
				Set<Provider.Service> services = p.getServices();
				for (java.security.Provider.Service service : services) {
					System.out.println(service);
				}
			}*/

			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "SC");
			// curveName这里取值：secp256k1
			ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("Secp256k1");
			keyPairGenerator.initialize(ecGenParameterSpec, new SecureRandom());
			keyPair = keyPairGenerator.generateKeyPair();
			// 获取公钥
			keyPair.getPublic();
			// 获取私钥
			keyPair.getPrivate();
			return keyPair;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void savePublicKeyAsPEM(PublicKey publicKey, String name,Context context) throws Exception {
		String content = new String(Base64.encode(publicKey.getEncoded(), Base64.DEFAULT));
		File file = new File(getPath(context,1),name);
		if (file.isFile() && file.exists())
			throw new IOException("file already exists");
		try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
			randomAccessFile.write("-----BEGIN PUBLIC KEY-----\n".getBytes());
			int i = 0;
			for (; i < (content.length() - (content.length() % 64)); i += 64) {
				randomAccessFile.write(content.substring(i, i + 64).getBytes());
				randomAccessFile.write('\n');
			}

			randomAccessFile.write(content.substring(i, content.length()).getBytes());
			randomAccessFile.write('\n');

			randomAccessFile.write("-----END PUBLIC KEY-----".getBytes());
		}
	}

	public static void savePrivateKeyAsPEM(PrivateKey privateKey, String name,Context context) throws Exception {
		String content = new String(Base64.encode(privateKey.getEncoded(), Base64.DEFAULT));
		File file = new File(getPath(context,1),name);
		if (file.isFile() && file.exists()){
			Log.e("TAG", "savePrivateKeyAsPEM: "+file.getPath() );
			throw new IOException("file already exists");
		}
		try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
			randomAccessFile.write("-----BEGIN PRIVATE KEY-----\n".getBytes());
			int i = 0;
			for (; i < (content.length() - (content.length() % 64)); i += 64) {
				randomAccessFile.write(content.substring(i, i + 64).getBytes());
				randomAccessFile.write('\n');
			}

			randomAccessFile.write(content.substring(i, content.length()).getBytes());
			randomAccessFile.write('\n');

			randomAccessFile.write("-----END PRIVATE KEY-----".getBytes());
		}
	}

	public static String getFilePath(Context context) {
		String directoryPath = "";
//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ) {//判断外部存储是否可用
		directoryPath = context.getExternalFilesDir("").getAbsolutePath();
        /*}else{//没外部存储就使用内部存储
            directoryPath=context.getFilesDir().getAbsolutePath();
        }*/

		File file = new File(directoryPath);
		if (!file.exists()) {//判断文件目录是否存在
			file.mkdirs();
		}
		return directoryPath + File.separator;
	}

	public static String getPath(Context context, int type) {
		String path;
		switch (type) {
			case 1:
				path = getFilePath(context) + "ecc/keys/";
				break;
			default:
				path = getFilePath(context) + "glide/image/";
				break;
		}

		File file = new File(path);
		if (!file.exists()) {
			if (file.mkdirs()) {
				return path;
			}
		}
		return path;
	}
}
